import echarts from 'echarts'
// import Vue from 'vue';
import waves from "@/directive/waves"; // Waves directive
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
// import { alertMessage, alertWithCallback, isValidateNull } from "@/utils/utils";
import { mapGetters } from 'vuex';
import selectDevice from "@/business-components/select-device/select-device";
import carDetail from "@/business-components/car-detail/car-detail"
import { getCompanyItems, getAreaList, getRealtimeCarStatisticApi, getRealtimeCarListApi, getRealtimeStatisticApi, getRealtimePercentStatisticApi } from "@/views/realtime-monitor/realtime-monitor.service";

export default {
  components: { Pagination, selectDevice, carDetail },
  directives: { waves },
  data() {
    return {
      intervalInstance: null, // 实例
      file_url: process.env.VUE_APP_FILE_URL, // 头像url
      recordNum: 20, // 分页组件默认的页数, 分页里的select默认10, 20, 50
      totalNum: 0, // 数据总数
      pageNum: 1, // 页数
      areaList: [], // 行政区list
      carList: [], // 车辆列表
      markers: [],
      searchCriteria: {}, // 搜索条件
      realtimeData: {}, // 实时数据
      showStatistic: false,
      veDisTime: '',
      currentInfoWindow: null,
      currentMarker: null,
      companies: [] // 运输单位
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    // 获取行政区下拉
    this.getAreas();
    // 获取运输单位下拉
    this.getCompanyList();
    // 获取统计数据
    this.getRealtimeData();
    // 获取实时车辆列表
    // this.getRealtimeCarList();
    this.intervalInstance = setInterval(() => {
      this.getMarkers();
    }, 5000)
  },
  beforeDestroy() {
    this.intervalInstance && clearInterval(this.intervalInstance);
  },
  mounted() {
  },
  methods: {
    // 获取行政区
    getAreas() {
      getAreaList().then(res => {
        this.areaList = res.data
      })
    },

    // 初始化地图
    initMap() {
      setTimeout(() => {
        this.map = new AMap.Map('map-container', {
          resizeEnable: true // 是否监控地图容器尺寸变化
        });
        this.currentInfoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(20, -17),
          content: ''
        });
        this.setMarker();
      }, 200);
    },

    // 运输单位列表
    getCompanyList() {
      getCompanyItems().then(res => {
        this.companies = res.data;
      });
    },

    // 获取车辆统计数据
    getRealtimeData() {
      this.searchCriteria.pageNum = this.pageNum;
      this.searchCriteria.recordNum = this.recordNum;
      getRealtimeCarStatisticApi(this.searchCriteria).then(res => {
        this.realtimeData = res.data;
        this.getRealtimeCarList();
      })
    },

    // 获取车辆统计数据
    getRealtimeCarList() {
      this.searchCriteria.pageNum = this.pageNum;
      this.searchCriteria.recordNum = this.recordNum;
      getRealtimeCarListApi(this.searchCriteria).then(res => {
        this.carList = res.data;
        this.markers = [];
        res.data.forEach(element => {
          if (element.realTimeInfo) {
            element.info =
              '<div>' +
              '<div> 车牌号码:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.licensePlate + '</span>' + '</div>' +
              '<div> 车辆名称:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.vehicleName + '</span>' + '</div>' +
              '<div> GPS地址:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + `${element.realTimeInfo.lonAndLat.lat},${element.realTimeInfo.lonAndLat.lng}` + '</span>' + '</div>' +
              '<div> 排放累计时长:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.realTimeInfo.disTimeAll + '</span>' + '</div>' +
              '<div> 排放次数:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.realTimeInfo.disCount + '</span>' + '</div>' +
              '<div> 运输单位:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.compName + '</span>' + '</div>' +
              '<div> 联系人:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.contact + '</span>' + '</div>' +
              '<div> 联系方式:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.phone + '</span>' + '</div>' +
              '</div>';
            this.markers.push(element)
          }
        })
        this.initMap();
      })
    },

    // generate info
    generateInfo(element) {
      const that = this;
      // 构建信息窗体中显示的内容
      const info = [];
      info.push('<div>');
      info.push('<div class="tag-container">');
      if (element.realTimeInfo.isWarningDis == '1') {
        info.push('<div class="warning-tag"><img src="' + require("@/assets/imgs/warning-yellow.png") + '" />排放报警</div>');
      }
      if (element.realTimeInfo.isOverFail == '1') {
        info.push('<div class="warning-tag"><img src="' + require("@/assets/imgs/warning-yellow.png") + '" />油气超压报警</div>');
      }
      if (element.realTimeInfo.isAirtightness == '1') {
        info.push('<div class="warning-tag"><img src="' + require("@/assets/imgs/warning-yellow.png") + '" />油罐气密性报警</div>');
      }
      if (element.realTimeInfo.isPowerFail == '1') {
        info.push('<div class="warning-tag"><img src="' + require("@/assets/imgs/warning-yellow.png") + '" />设备断电报警</div>');
      }
      info.push('</div>');
      info.push('<div>车牌号码:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.licensePlate + '</span>' + '</div>');
      info.push('<div>车辆名称:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.vehicleName + '</span>' + '</div>');
      info.push('<div>运输单位:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.compName + '</span>' + '</div>');
      info.push('<div>排放累计时长:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.realTimeInfo.disTimeAll + '</span>' + '</div>');
      info.push('<div>排放次数:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.realTimeInfo.disCount + '</span>' + '</div>');
      info.push('<div>联系人:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.contact + '</span>' + '</div>');
      info.push('<div>联系方式:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.phone + '</span>' + '</div>');
      info.push('</div>');
      this.currentInfoWindow.setContent(info.join(''));
      this.currentInfoWindow.open(that.map, [element.realTimeInfo.lonAndLat.lng, element.realTimeInfo.lonAndLat.lat]);
    },

    // 获取车辆统计数据
    getMarkers() {
      this.searchCriteria.pageNum = this.pageNum;
      this.searchCriteria.recordNum = this.recordNum;
      getRealtimeCarListApi(this.searchCriteria).then(res => {
        this.markers = [];
        res.data.forEach(element => {
          if (element.realTimeInfo) {
            element.info =
              '<div>' +
              '<div> 排放报警:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.licensePlate + '</span>' + '</div>' +
              '<div> 车牌号码:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.licensePlate + '</span>' + '</div>' +
              '<div> 车辆名称:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.vehicleName + '</span>' + '</div>' +
              '<div> GPS地址:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + `${element.realTimeInfo.lonAndLat.lat},${element.realTimeInfo.lonAndLat.lng}` + '</span>' + '</div>' +
              '<div> 排放累计时长:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.realTimeInfo.disTimeAll + '</span>' + '</div>' +
              '<div> 排放次数:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.realTimeInfo.disCount + '</span>' + '</div>' +
              '<div> 运输单位:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.compName + '</span>' + '</div>' +
              '<div> 联系人:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.contact + '</span>' + '</div>' +
              '<div> 联系方式:' + '<span class="aq-padding-left-8 aq-text-color-primary">' + element.phone + '</span>' + '</div>' +
              '</div>';
            this.markers.push(element)
          }
        });
        this.setMarker();
      })
    },

    // 添加点标记
    setMarker() {
      this.map.remove(this.map.getAllOverlays('marker'));
      let that = this;
      if (!this.markers) {
        return
      }
      for (let i = 0; i < this.markers.length; i++) {
        // 如果车辆有实时数据的情况
        if (this.markers[i].realTimeInfo) {
          let url = require("@/assets/imgs/car-img-normal.png");
          if (this.markers[i].realTimeInfo.isOverFail == 1 || this.markers[i].realTimeInfo.isWarningDis == 1 || this.markers[i].realTimeInfo == 1 || this.markers[i].realTimeInfo == 1) {
            url = require("@/assets/imgs/car-img.png");
          }
          let marker = new AMap.Marker({
            position: new AMap.LngLat(this.markers[i].realTimeInfo.lonAndLat.lng, this.markers[i].realTimeInfo.lonAndLat.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: this.markers[i].vehicleName,
            icon: new AMap.Icon({
              size: new AMap.Size(64, 64),
              imageSize: new AMap.Size(64, 64),
              image: url // 添加 Icon 图标 URL
            }),
            extData: this.markers[i]
          });
          // 修复信息窗口不跟随车刷新问题
          if (that.currentMarker && that.currentMarker.objectId === this.markers[i].objectId) {
            that.generateInfo(this.markers[i]);
          }
          marker.on('mouseover', (e) => { // 鼠标悬浮显示window info
            // 修复信息窗口不跟随车刷新问题
            this.markers.forEach(ele => {
              ele.reload = false
            })
            this.markers[i].reload = true;
            that.generateInfo(this.markers[i]);
            that.currentMarker = this.markers[i];
            // markerInfo(marker);
          });
          marker.on('click', (e) => { // 鼠标点击icon
            that.showStatistic = true
            that.getLineChart(marker);
            that.getPieChart(marker);
          });
          this.map.add(marker);
        }
      }
      // 缩放地图到合适的视野级别
      // function markerInfo(e) {
      //   let markerInfo = e.getExtData();
      //   let markerPosition = e.getExtData();
      //   // 自定义窗体
      //   var infoWindow = new AMap.InfoWindow({
      //     offset: new AMap.Pixel(20, -30)
      //   });
      //   // 自定义窗体交互事件
      //   let InfoContent = Vue.extend({
      //     template: `${markerInfo.info}`
      //   })
      //   let component = new InfoContent().$mount()
      //   infoWindow.setContent(component.$el);
      //   // 打开自定义窗体
      //   infoWindow.open(that.map, [markerPosition.realTimeInfo.lonAndLat.lng, markerPosition.realTimeInfo.lonAndLat.lat]);
      // }
    },

    // 根据关键字进行搜索
    search() {
      this.showStatistic = false;
      this.pageNum = 1;
      this.getRealtimeData();
    },

    // 重置搜索
    reset() {
      this.pageNum = 1;
      this.searchCriteria = {};
      this.getRealtimeData();
    },

    // 获取折线图数据
    getLineChart(e) {
      let markerInfo = e.getExtData();
      const data = {
        vehicleId: markerInfo.objectId,
        statisType: 1
      }
      getRealtimeStatisticApi(data).then(res => {
        let xAxis = [];
        let yAxis = [];
        res.data.forEach(element => {
          xAxis.push(element.queryDate);
          yAxis.push(element.disCurrentTime)
        })
        const lineChart = echarts.init(document.getElementById('lineChart'), 'light');
        lineChart.setOption(
          {
            title: {
              text: '排放时长数据折线图',
              textStyle: {
                color: '#fff',
                fontSize: 14
              }
            },
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: [markerInfo.vehicleName],
              textStyle: {
                color: '#fff',
                fontSize: 14
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xAxis,
              axisLabel: {
                color: '#ffffff'
              }
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                color: '#ffffff'
              }
            },
            series: [
              {
                name: markerInfo.vehicleName,
                type: 'line',
                data: yAxis
              }
            ]
          }
        )
      })
    },

    // 获取饼状图
    getPieChart(e) {
      let markerInfo = e.getExtData();
      getRealtimePercentStatisticApi(markerInfo.objectId).then(res => {
        this.veDisTime = res.data.veDisTime;
        const pieChart = echarts.init(document.getElementById('pieChart'), 'light');
        pieChart.setOption(
          {
            title: {
              text: '%占平台总排放时长',
              textStyle: {
                color: '#fff',
                fontSize: 14
              }
            },
            tooltip: {
              trigger: 'item',
              formatter: '{b} : {c} ({d}%)'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            series: [
              {
                name: markerInfo.vehicleName,
                type: 'pie',
                radius: '55%',
                data: [
                  { value: res.data.veDisTime, name: markerInfo.vehicleName },
                  { value: res.data.allDisTime - res.data.veDisTime, name: '其他' }
                ]
              }
            ]
          }
        )
      })
    }
  }
}
